<?php

class admin extends Model
{

	function count( $name ) {
		return $this->db->getAll("SELECT count(admin.admin_id)
			FROM admin, user, organization
			WHERE admin.org_id = organization.org_id
			AND admin.stud_no = user.stud_no
			AND admin.org_id = ?
			ORDER BY admin_id ASC",
			array( (int)$id )
		);
	}

	function findNotAdminByName( $name, $org ) {
		return $this->db->getAll(
			"
			SELECT DISTINCT 
				u.stud_no,
				u.lastname,
				u.firstname
			FROM 
				user u LEFT JOIN admin a ON u.stud_no = a.stud_no
			WHERE
				( lastname LIKE ?
				OR
				firstname LIKE ? 
				OR u.stud_no LIKE ?
				)
				AND
				( u.stud_no NOT IN (SELECT stud_no FROM admin WHERE org_id = ?) )
				AND
				(u.admin = 2)",
			array( "%$name%", "%$name%", "%$name%", $org )
		);
	}

	function getAdmin($id) {
		return $this->db->getAll("
			SELECT
			u.stud_no,
			u.firstname,
			u.lastname,
			u.middlename
			FROM `organization` o INNER JOIN user u ON u.stud_no = o.professor
			WHERE o.org_id =?",
			array( (int) $id )
		);
	}
	
	function getAdminOrg($id) {
		$gadmin = $this->db->getAll("SELECT 
				admin.admin_id,
				organization.org_id,
				organization.name Org
			FROM admin, user, organization
			WHERE admin.stud_no = user.stud_no
			AND user.stud_no = ? ",
			array( (int)$id )	
		);
		return $gmember;
	}

	function amIAdmin($studno, $orgid) {
//		$ids = $this->db->getAll("
//			SELECT admin.admin_id
//			FROM admin
//			WHERE stud_no = ?
//			AND org_id = ?
//			",
//			array( $studno, (int) $orgid )
//		);
//		if( count( $ids ) > 0 ) return true;
//		else return false;
		$id = $this->db->getOne('SELECT professor FROM organization WHERE org_id = ?', array(
			$orgid
		) );
		if( $id == $studno ) return true;
		else return false;
	}
	
	function amIAdminByName($studno, $orgname) {
		return $this->db->getAll("
			SELECT a.admin_id
			FROM admin a, organization o
			WHERE a.stud_no = ?
			AND o.name = ?
			",
			array( $studno, $orgname ) 
		);
	}
	
	function insertAdmin( $stud_no, $org_id ) {
		$iadmin = $this->db->execute("INSERT INTO admin( stud_no, org_id )
			VALUES ( ?, ? )", 
			array( $stud_no, $org_id )
		);
		return $iadmin;
	}

	function updateAdmin( $org_id, $admin_id ) 
	{
		$uadmin = $this->db->execute("UPDATE admin
			SET org_id = ?
			WHERE admin_id = ?",
			array( $org_id, $admin_id )
		);
		return $uadmin;
	}

	function deleteAdmin ( $admin_id )
	{
		$dadmin = $this->db->execute("DELETE FROM admin
			WHERE admin_id = ? ",
			array( $admin_id )
		);
	}
	
	function deleteAdminByStudent( $stud_no, $orgid ) {
		$dadmin = $this->db->execute("DELETE FROM admin
			WHERE stud_no = ?  AND org_id = ?",
			array( $stud_no, (int) $orgid )
		);
	}
	
}